package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Override   //      分类列表
    public List<Category> findAll() {
        List<Category> list=categoryMapper.findAll();
        return list;
    }

    @Override //新增菜品、套餐
    public void save(Category category) {
        //补齐参数
        long id = IdUtil.getSnowflake(1, 1).nextId();
        category.setId(id);
        /*category.setUpdateTime(new Date());
        category.setCreateTime(new Date());
        category.setUpdateUser(1L);//暂时写死管理员1
        category.setCreateUser(1L);*/
        categoryMapper.save(category);
    }

    @Override//修改菜品、套餐
    public void update(Category category) {
        //补齐参数
       /* category.setUpdateUser(1L);
        category.setUpdateTime(new Date());*/
        //categoryMapper.update(category);
        categoryMapper.updateById(category);
    }

    @Override
    public void delete(Long id) {
        Integer count1=categoryMapper.countDishByCategoryId(id);
        if(count1>0){
            throw new CustomException("该分类下还有菜品，无法删除");
        }
        Integer count2=categoryMapper.countSetmealByCategoryId(id);
        if(count2>0){
            throw new CustomException("该套餐下还有菜品，无法删除");
        }
        categoryMapper.delete(id);
    }

    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);
        List<Category> list = categoryMapper.selectList(wrapper);
        return list;
    }
}
